from flask import current_app
from flask import Blueprint,  request, jsonify,render_template,session
from decorator import login_required
from bt import Bt_api
import re
# 移除缓存导入，因为我们不再使用缓存

blueprint = Blueprint('/traffic', __name__, url_prefix='/traffic')


# 前端
@blueprint.route("/logs", endpoint='logs', methods=['GET', 'POST'])
@login_required
def logs():
    cdn=current_app.config['CDN']
    
    return render_template('logs.html',cdn=cdn)
   
# 获取流量
@blueprint.route("/statistics", endpoint='statistics', methods=['GET', 'POST'])
@login_required
def statistics():
    # 移除缓存相关代码，直接从宝塔API获取数据
        
    # path = request.form.get('path')
    try:
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.GetSiteLogs(session.get('bt_web'))
      
     
        # 定义正则表达式模式
        pattern =  r'200\s+(\d+)'

        # 匹配字符串
        matches = re.findall(pattern, data['msg'])
        total = sum(int(n) for n in matches)
        
        # 移除缓存存储代码，直接返回数据

       
        return jsonify(total)
    except Exception as e:
        # 如果出现异常，返回错误信息
        return jsonify({'error': str(e)}), 500


# 获取网站操作日志
@blueprint.route("/webgetData", endpoint='webgetData', methods=['GET', 'POST'])
@login_required
def webgetData():
    # 移除缓存相关代码，直接从宝塔API获取数据
        
    # 记录所有接收到的参数
    current_app.logger.info(f"All form data: {request.form}")
    current_app.logger.info(f"All args data: {request.args}")
    
    # 获取分页参数（支持Bootstrap Table默认参数）
    # Bootstrap Table默认传递的参数是offset和limit
    offset = request.form.get('offset', 0)
    limit = request.form.get('limit', 10)
    
    # 记录原始获取的参数
    current_app.logger.info(f"Raw form params: offset={offset}, limit={limit}")
    current_app.logger.info(f"Raw args params: offset={request.args.get('offset')}, limit={request.args.get('limit')}")
    
    # 计算页码
    try:
        offset = int(offset)
        limit = int(limit)
        page = (offset // limit) + 1  # Bootstrap Table使用offset, 我们需要转换为页码
        current_app.logger.info(f"Calculated from form: page={page}")
    except (ValueError, TypeError) as e:
        current_app.logger.info(f"Error calculating page from form: {e}")
        page = 1
        limit = 10
    
    # 如果form中没有获取到参数，尝试从args中获取（GET参数）
    if (offset == 0 and limit == 10) and (request.args.get('offset') is not None or request.args.get('limit') is not None):
        offset = request.args.get('offset', 0)
        limit = request.args.get('limit', 10)
        try:
            offset = int(offset)
            limit = int(limit)
            page = (offset // limit) + 1
            current_app.logger.info(f"Calculated from args: page={page}")
        except (ValueError, TypeError) as e:
            current_app.logger.info(f"Error calculating page from args: {e}")
            page = 1
            limit = 10
    
    # 记录调试信息
    current_app.logger.info(f"Received pagination params: offset={offset}, limit={limit}, calculated page={page}")
    
    # 添加更多调试信息
    current_app.logger.info(f"Session bt_web: {session.get('bt_web')}")
    
    try:
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        
        # 记录调试信息
        current_app.logger.info(f"Calling webgetData with params: search={session.get('bt_web')}, page={page}, limit={limit}")
        
        # 修改webgetData方法调用，传递分页参数
        data = bt_api.webgetData(session.get('bt_web'), page, limit)
        
        # 记录返回的数据
        current_app.logger.info(f"Returned data: {data}")
        current_app.logger.info(f"Returned data type: {type(data)}")
        if isinstance(data, dict):
            current_app.logger.info(f"Returned data keys: {data.keys()}")
            current_app.logger.info(f"Data field type: {type(data.get('data'))}")
            if 'data' in data and isinstance(data['data'], list):
                current_app.logger.info(f"Data field length: {len(data['data'])}")
            if 'page' in data:
                current_app.logger.info(f"Page field: {data['page']}")
        current_app.logger.info(f"Returned data length: {len(data.get('data', [])) if isinstance(data, dict) and 'data' in data else 'N/A'}")
       
        # 检查返回的数据是否包含分页信息
        if isinstance(data, dict) and 'page' in data:
            # 确保page字段包含正确的分页信息
            page_info = data['page']
            current_app.logger.info(f"Page info: {page_info}")
            
            # 如果page_info是字符串，尝试从中提取总记录数
            if isinstance(page_info, str):
                import re
                match = re.search(r'共(\d+)条', page_info)
                if match:
                    total_count = int(match.group(1))
                    current_app.logger.info(f"Total count from page info: {total_count}")
                    # 在返回的数据中添加total字段
                    data['total'] = total_count
        
        # 直接返回宝塔API的完整响应
        return jsonify(data)
    except Exception as e:
        # 如果出现异常，返回错误信息
        current_app.logger.error(f"Error in webgetData: {str(e)}")
        return jsonify({'error': str(e)}), 500